package pl.darbat.photogallery.html;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import pl.darbat.photogallery.Debug;

import android.util.Log;

public class HtmlDownloader extends Thread{
	
	private static final String TAG = "HtmlDownloader";
	private HtmlDownloaderListener mHtmlDownloaderListener;
	private URL mUrl;
	
	public void asyncDownloadPage(URL url){
		if (Debug.HTMLDOWNLOADER) Log.v(TAG,"asyncDownloadPage");
		if(url != null){
			if(mHtmlDownloaderListener != null ){
				mUrl = url;
				this.start();
			} else {
				throw new IllegalStateException("HtmlParserListener is not set.");
			}
		} else {
			throw new IllegalArgumentException("HtmlParserListener is not set.");
		}
	}
	
	@Override
	public void run() {
		mHtmlDownloaderListener.onDownloadResult(downloadPage(mUrl));
	}

	public InputStream downloadPage(URL url) {
		if (Debug.HTMLDOWNLOADER) Log.v(TAG,"downloadPage");
		try {	
			return mUrl.openStream();
		} catch (IOException e) {
			Log.e(TAG,"",e);
			return null;
		}
	}

	public void setHtmlDownloaderListener(HtmlDownloaderListener htmlDownloaderListener) {
		if (Debug.HTMLDOWNLOADER) Log.v(TAG,"setHtmlDownloaderListener");
		mHtmlDownloaderListener = htmlDownloaderListener;
	}
}
